package com.exchange.used.config.filter;

import com.exchange.used.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/src/*", "*.html"})
public class LoginFilter implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1,
                         FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        User user = (User) request.getSession().getAttribute("user");
        String requestURL = request.getRequestURI();
        if (user == null && !requestURL.endsWith("login.html") && !requestURL.endsWith("register.html")) {
            response.sendRedirect("/");
            return;
        }
        arg2.doFilter(request, response);
    }

    public void init(FilterConfig arg0) {
    }
}
